<script setup lang="ts">
import dayjs from 'dayjs'
import AppEmojiPicker from '~/components/AppEmojiPicker.vue'
import AppSelect from '~/components/AppSelect.vue'
import BaseImage from '~/components/BaseImage.vue'
import arrowDown from '/images/webp/affiliate-program/arrow-down.webp'
import chatSend from '/images/webp/affiliate-program/chat-send.webp'
import chatSendActive from '/images/webp/affiliate-program/send_active.webp'
// 添加useI18n
const { t } = useI18n()
const router = useRouter()
// 语言选择相关
interface LanguageOption {
  label: string
  value: string
}
/**
 * 用户级别
 */
type UserLevelBadge = 'bronze' | 'silver' | 'gold' | 'diamond' | '1' | '2' | '3' | '4'
/**
 * 聊天室用户角色
 */
type ChatUserRole = 'moderator'

/**
 * 聊天室用户
 */
interface ChatUserInfo {
  name: string
  uid: string
  level?: UserLevelBadge
  role?: ChatUserRole
  [k: string]: any
}

/**
 * 聊天室消息体
 */
interface ChatMessageInfo {
  id?: string
  i?: string
  c?: string
  n?: string
  u?: string
  t?: number
  type?: 'tip' | 'rain'
  user: ChatUserInfo
  msg?: string
  isSelf?: boolean
  isAdmin?: boolean
  [k: string]: any
}

// 集成聊天室状态管理
const chatStore = useChatStore()
const { hideChat, deletedMsgs, room, topic, topic_del_msg,enableChat } = storeToRefs(chatStore)
const { userInfo } = storeToRefs(useAppStore())
const pageSize = 25
const page = 1
const scrollMsg = ref()
const chatMessage = ref('')
const msgCounter = ref(1)
const currentLanguage = ref('')
const languageOptions = ref<LanguageOption[]>([
  { label: '全球', value: '' },
  { label: 'English', value: 'en_US' },
  { label: '简体中文', value: 'zh_CN' },
  { label: 'ไทย', value: 'th_TH' },
  { label: 'Tiếng Việt', value: 'vi_VN' },
  { label: '日本語', value: 'ja_JP' }
])
const messageHistory = ref<Array<ChatMessageInfo>>([])
const appSelectRef = ref()
useChatEvent()
const {
  bool: msgHistoryLoading,
  setFalse: setMHLFalse,
  setTrue: setMHLTrue,
} = useBoolean(false)
const { bool: showMoreBar, setFalse: setMFalse, setTrue: setMTrue } = useBoolean(false)

const showRulesDialog = ref(false)
const showChatUnlockDialog = ref(false)
const showEmojiPicker = ref(false)
const inputFocused = ref(false)
const maxMsgLen = 160
// 处理表情选择
function handleEmojiSelect(emoji: string) {
  chatMessage.value += emoji
}

// 处理输入框焦点
function handleInputFocus() {
  inputFocused.value = true
}

function handleInputBlur() {
  inputFocused.value = false
}

definePageMeta({
  layout: 'footer-layout'
});

// MQTT连接成功的处理函数
function onMqttConnectSuc() {
  console.log('MQTT连接成功，设置聊天主题');
  // 先移除现有订阅，避免重复
  socketClient.removeSubscribe(topic.value)
  socketClient.removeSubscribe(topic_del_msg.value)

  // 重新添加订阅
  setTimeout(() => {
    addChatTopic()
    delChatTopic()
  }, 0)
}

// 添加聊天消息主题订阅
function addChatTopic() {
  console.log('添加聊天消息主题订阅:', topic.value);
  socketClient.addSubscribe(topic.value, { callback: addChatCallback })
}

// 添加聊天删除消息主题订阅
function delChatTopic() {
  console.log('添加聊天删除消息主题订阅:', topic_del_msg.value);
  socketClient.addSubscribe(topic_del_msg.value, { callback: delChatCallback })
}

// 过滤已删除的消息
const filteredMessageHistory = computed(() => {
  const history = messageHistory.value
  const deletedIds = deletedMsgs.value

  if (!history || !history.length)
    return []

  return history
    .filter((item: ChatMessageInfo) => !item.i || !deletedIds.includes(item.i))
    .slice(-52)
})

// 使用API获取历史消息
const { run: runGetHistory } = useRequest(ApiChatGetHistory, {
  onBefore: () => {
    setMHLTrue()
  },
  onSuccess: (data: any) => {
    if (data && data.d && data.d.length)
      messageHistory.value = data.d?.reverse().map((m: any) => ({
        ...m,
        id: m.i,
        msg: m.c,
        user: { name: m.n, uid: m.u },
        // 判断消息是否为当前用户发送
        isSelf: isCurrentUser(m.u),
        // 判断消息是否为管理员发送
        isAdmin: isAdmin(m.u, m.n)
      }))
    else
      messageHistory.value = []
  },
  onAfter: () => {
    setTimeout(() => {
      goBottom()
      setMHLFalse()
    }, 800)
  },
})

watch(enableChat, (val) => {
  if (!val)
  chatMessage.value = ''
})

// 判断消息是否为当前用户发送
function isCurrentUser(uid: string): boolean {
  // 使用userInfo.value.uid判断是否为当前用户发送
  return uid === userInfo.value.uid
}

// 获取当前用户ID
function getCurrentUserId(): string {
  // 这里模拟从用户系统中获取用户ID的逻辑
  return '1234567890'  // 返回一个模拟的用户ID
}

// 判断消息是否为管理员发送
function isAdmin(uid: string, name: string): boolean {
  // 主播和管理员均会显示为特殊角色
  // 这里根据用户ID或者名字来判断是否为管理员
  return name.includes('BC.GAME') || name.includes('Admin')
}



// 监听滚动位置
function messageWrapScroll() {
  if (msgHistoryLoading.value)
    return
  if (scrollMsg.value) {
    const { height } = scrollMsg.value.getBoundingClientRect()
    // 当滚动位置距离底部超过200px时，显示"更多消息"按钮
    if (scrollMsg.value.scrollHeight - scrollMsg.value.scrollTop - height > 200) {
      console.log('显示更多消息按钮')
      setMTrue()
    }
    else {
      console.log('隐藏更多消息按钮')
      setMFalse()
    }
  }
}

// 切换聊天室语言
function roomChange(room: string) {
  console.log('切换聊天室到:', room);

  // 先取消现有订阅
  socketClient.removeSubscribe(topic.value)

  // 更新语言和房间
  nextTick(() => {
    scrollMsg.value.scrollTop = 0
  })

  // 设置当前语言
  currentLanguage.value = room

  // 告诉store房间已更改(需要确保chatStore有setRoom方法)
  // chatStore.setRoom({ value: room })

  // 获取新房间的历史消息
  runGetHistory({ lang: room, page, page_size: pageSize })
  setMFalse()

  // 重新订阅新房间的主题
  setTimeout(() => {
    addChatTopic()
  }, 0)
}

// 获取当前选择的语言标签
const currentLanguageLabel = computed(() => {
  const option = languageOptions.value.find((option: LanguageOption) => option.value === currentLanguage.value)
  return option ? option.label : '全球'
})

// 打开语言选择
function openLanguageSelect() {
  appSelectRef.value?.openSelect()
}

// 滚动到底部
function goBottom2() {
  nextTick(() => {
    setTimeout(() => {
      if (scrollMsg.value) {
        const { height } = scrollMsg.value.getBoundingClientRect()
        scrollMsg.value.scrollTop = scrollMsg.value.scrollHeight - height + 500
      }
    }, 30)
  })
}

function goBottom(time?: number) {
  nextTick(() => {
    setTimeout(() => {
      document.querySelector('.msg-tail')?.scrollIntoView({ behavior: 'smooth' })
    }, time !== void 0 ? time : 300)
  })
}

// 发送消息处理
function sendMessage() {
  if (!chatMessage.value.trim()) return

  // 检查是否需要解锁聊天功能
  if (needToUnlockChat()) {
    showChatUnlockDialog.value = true
    return
  }

  // 发送消息到服务器
  // 这里应该使用你的API发送消息
  const messageData = {
    c: chatMessage.value,
    lang: currentLanguage.value || 'en_US',
    i: generateMessageId(), // 生成一个临时消息ID
    v: '1.0' // 假设需要版本号
  }

  // 清空输入框
  chatMessage.value = ''

  // 使用API发送消息
  ApiChatSendMessage(messageData).then(() => {
    // 消息发送成功后，滚动到底部
    goBottom(0)
  }).catch((error) => {
    console.error('Failed to send message:', error)
  })
}

// 生成临时消息ID
function generateMessageId(): string {
  return 'msg_' + Date.now() + '_' + Math.floor(Math.random() * 1000)
}

// 检查是否需要解锁聊天功能
function needToUnlockChat() {
  // 根据业务逻辑判断是否需要解锁聊天
  // 这里简单示例，实际应该根据用户状态判断
  return false // 暂时返回false，表示不需要解锁
}

// 接收新消息处理
function onReceiveChatMsg(m: any) {
  console.log('收到聊天消息:', m);
  // 检查消息是否已存在 (防止重复)
  const hasMsg = m.i && messageHistory.value && messageHistory.value.length
    ? isValueContainInBloom(messageHistory.value.map((v: any) => v.i).filter((f: any) => f !== void 0 && f.length), m.i)
    : false

  if (!hasMsg) {
    console.log('添加新消息到列表')
    // 如果消息不存在，添加到消息列表
    if (!messageHistory.value || !messageHistory.value.length)
      messageHistory.value = []

    // 添加新消息到列表
    messageHistory.value.push({
      ...m,
      id: m.i,
      msg: m.c,
      user: { name: m.n, uid: m.u },
      isSelf: isCurrentUser(m.u),
      isAdmin: isAdmin(m.u, m.n)
    })

    // 如果已经滚动离开底部，增加新消息计数
    // 否则自动滚动到底部显示新消息
    if (showMoreBar.value) {
      console.log('增加新消息计数')
      msgCounter.value += 1
    }
    else {
      console.log('滚动到新消息')
      goBottom2()
    }
  }
}

// 删除消息处理
function onDelMsgItem(delId: any) {
  console.log('删除消息:', delId)
  chatStore.setDelMsgs(delId)
}

// 监听更多消息栏状态变化
watch(showMoreBar, (val: boolean) => {
  if (!val)
    msgCounter.value = 1
})

// 监听聊天窗口隐藏状态变化
watch(hideChat, (val: boolean) => {
  if (val) {
    // 如果聊天被隐藏，移除订阅
    console.log('聊天被隐藏，移除订阅');
    socketClient.removeSubscribe(topic.value)
    socketClient.removeSubscribe(topic_del_msg.value)
  }
  else {
    // 如果聊天被显示，添加订阅
    console.log('聊天被显示，添加订阅');
    setTimeout(() => {
      addChatTopic()
      delChatTopic()
    }, 0)
  }
})

// 时间格式化
function formatTime(timestamp: number): string {
  return dayjs(timestamp).format('HH:mm')
}

// 获取星期几
function getDayOfWeek(timestamp: number): number {
  return dayjs(timestamp).day()
}

// 检查时间戳是否有效
function checkTs(timestamp?: number): number {
  return timestamp || Date.now()
}

// 初始化
onMounted(() => {
  // 设置滚动处理
  setTimeout(() => {
    const allScrollyEl = document.querySelectorAll('.chat-content')
    // 这里应该使用项目中的滚动锁定功能，如果有的话
  }, 300)

  // 获取初始消息历史
  runGetHistory({ lang: currentLanguage.value || 'en_US', page, page_size: pageSize })

  // 订阅MQTT事件总线
  console.log('设置聊天消息监听器');
  appEventBus.on(EventBusNames.CHAT_MESSAGE_BUS, onReceiveChatMsg)
  appEventBus.on(EventBusNames.CHAT_DEL_MESSAGE_BUS, onDelMsgItem)

  // 监听MQTT连接成功事件
  console.log('监听MQTT连接成功事件')
  appEventBus.on(EventBusNames.MQTT_CONNECT_SUCCESS_BUS, onMqttConnectSuc)

  // 初始化聊天主题订阅
  setTimeout(() => {
    console.log('初始化聊天主题订阅')
    addChatTopic()
    delChatTopic()
  }, 0)
})

onUnmounted(() => {
  // 取消订阅事件总线
  console.log('移除聊天消息监听器');
  appEventBus.off(EventBusNames.CHAT_MESSAGE_BUS, onReceiveChatMsg)
  appEventBus.off(EventBusNames.CHAT_DEL_MESSAGE_BUS, onDelMsgItem)

  // 移除MQTT连接成功事件监听
  appEventBus.off(EventBusNames.MQTT_CONNECT_SUCCESS_BUS, onMqttConnectSuc)

  // 移除聊天主题订阅
  console.log('移除聊天主题订阅')
  socketClient.removeSubscribe(topic.value)
  socketClient.removeSubscribe(topic_del_msg.value)
})
</script>

<template>
  <div class="chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="header-left">
        <div class="language-trigger" @click="openLanguageSelect">
          <span class="global-label">{{ currentLanguageLabel }}</span>
          <BaseImage width="12px" :url="arrowDown" />
        </div>
        <div class="online-status">
          <i class="online-dot" />
          <span class="online-text">{{ t('chat_online') }}：9,810</span>
        </div>
      </div>
      <div class="header-right">
        <div class="icon-info-container" @click="showRulesDialog = true">
          <i class="icon-info" />
        </div>
        <div class="icon-info-container" @click="router.back">
          <i class="icon-close" />
        </div>
      </div>
    </div>

    <!-- 如果聊天被隐藏，显示被隐藏的提示 -->
    <div v-if="hideChat" class="stack x-center y-center direction-vertical gap-small padding-none"
      style="height: calc(100% - 48px);">
      <div class="popped-chat-wrapper">
        <span>{{ $t('chat_been_hide') }}</span>
        <button class="deposit-btn" @click="chatStore.toggleChat">
          {{ $t('chat_show_room') }}
        </button>
      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div v-else class="chat-content" ref="scrollMsg" @scroll="messageWrapScroll">
      <div class="message-list">
        <!-- 聊天加载中显示骨架屏 -->
        <template v-if="msgHistoryLoading">
          <div v-for="i in 10" :key="i" class="message-item loading-skeleton">
            <div class="skeleton-header"></div>
            <div class="skeleton-body"></div>
          </div>
        </template>

        <!-- 显示消息历史 -->
        <template v-else>
          <template v-for="(message, mdx) in filteredMessageHistory" :key="mdx">
            <!--            &lt;!&ndash; 时间分割线 &ndash;&gt;-->
            <!--            <div v-if="mdx > 0 && (checkTs(message.t) - checkTs(filteredMessageHistory[mdx - 1].t)) > 60000"-->
            <!--              class="time-wrap">-->
            <!--              <span>{{ $t(`week_${dayjs(checkTs(message.t)).day()}`) }}</span>-->
            <!--              <span>{{ dayjs(checkTs(message.t)).format('HH:mm') }}</span>-->
            <!--            </div>-->
            <!--            <div v-if="mdx === 0" class="time-wrap">-->
            <!--              <span>{{ $t(`week_${dayjs(checkTs(message.t)).day()}`) }}</span>-->
            <!--              <span>{{ dayjs(checkTs(message.t)).format('HH:mm') }}</span>-->
            <!--            </div>-->

            <!-- 消息项 -->
            <div class="message-item" :class="[
              message.isSelf ? 'message-self' : '',
              message.isAdmin ? 'message-admin' : '',
            ]">
              <div class="message-header">
                <div class="user-info">
                  <span v-if="!message.isSelf" class="username" :class="{ 'admin-name': message.isAdmin }">
                    <span v-if="message.isAdmin">@{{ message.user?.name || '' }}</span>
                    <span v-else>{{ message.user?.name || '' }}</span>
                  </span>
                  <span class="message-time" :class="{'time-self': message.isSelf}">{{ formatTime(message.t * 1000 || 0) }}</span>
                </div>
              </div>
              <div class="message-body">
                {{ message.msg || message.c || '' }}
              </div>
            </div>
          </template>

          <!-- 消息尾部标记，用于滚动定位 -->
          <div class="msg-tail"></div>
        </template>
      </div>

      <!-- 新消息提示 -->
<!--      <div v-if="showMoreBar && !msgHistoryLoading" class="more-wrap">-->
<!--        <button class="more-messages-btn" @click.stop="goBottom(0)">-->
<!--          <div class="icon-text stop">-->
<!--            <i class="icon-stop"></i>-->
<!--            <span>{{ $t('chat_stop_by_scroll') }}</span>-->
<!--          </div>-->
<!--          <div class="icon-text go-down">-->
<!--            <i class="icon-arrow-down"></i>-->
<!--            <span>{{ msgCounter }}+ {{ $t('chat_new_msgs_count') }}</span>-->
<!--          </div>-->
<!--        </button>-->
<!--      </div>-->
    </div>

    <!-- 聊天输入区域 -->
    <div class="chat-input-area">
      <div class="input-container">
        <div style="display: flex;width: 100%;gap: 8px;">
            <div class="input-with-emoji" :class="{ 'input-focused': inputFocused }">
            <input type="text" class="message-input" v-model="chatMessage" :placeholder="enableChat?t('chat_input_message'):t('forbid_chat_placeholder')"
              :disabled="!enableChat" @keyup.enter="sendMessage" @focus="handleInputFocus" @blur="handleInputBlur">
            <i class="emoji-icon" @click="showEmojiPicker = !showEmojiPicker" />
          </div>
          <button class="send-button" :disabled="maxMsgLen - chatMessage.length <= 0 || !enableChat" :class="{ activeChat: chatMessage.length > 0 }" @click="sendMessage">
            <BaseImage width="20px" height="17x" :url="chatMessage.length > 0 ? chatSendActive : chatSend" />
          </button>
        </div>

        <!-- Emoji Picker Component positioned below input field -->
        <div class="emoji-picker-container" v-if="showEmojiPicker">
          <AppEmojiPicker :show="true" @select="handleEmojiSelect" />
        </div>

      </div>
    </div>
    <div class="footer-spacer" />

    <!-- 聊天室规则弹框 -->
    <div v-if="showRulesDialog" class="dialog-overlay" @click="showRulesDialog = false">
      <div class="dialog rules-dialog" @click.stop>
        <div class="dialog-header">
          <h3>{{ t('chat_rules_title') }}</h3>
          <button class="close-btn" @click="showRulesDialog = false">
            <i class="icon-close" />
          </button>
        </div>
        <div class="dialog-content" style="padding-bottom: 40px;">
          <ol class="rules-list">
            <li>1.{{ t('chat_rules_item_1') }}</li>
            <li>2.{{ t('chat_rules_item_2') }}</li>
            <li>3.{{ t('chat_rules_item_3') }}</li>
            <li>4.{{ t('chat_rules_item_4') }}</li>
            <li>5.{{ t('chat_rules_item_5') }}</li>
            <li>6.{{ t('chat_rules_item_6') }}</li>
            <li>7.{{ t('chat_rules_item_7') }}</li>
            <li>8.{{ t('chat_rules_item_8') }}</li>
          </ol>
        </div>
      </div>
    </div>

    <!-- 解锁聊天功能弹框 -->
    <div v-if="showChatUnlockDialog" class="dialog-overlay" @click="showChatUnlockDialog = false">
      <div class="dialog unlock-dialog" @click.stop>
        <div class="dialog-header">
          <h3>{{ t('chat_unlock_title') }}</h3>
          <button class="close-btn" @click="showChatUnlockDialog = false">
            <i class="icon-close" />
          </button>
        </div>
        <div class="dialog-content unlock-content">
          <div class="telegram-icon" />
          <p class="unlock-text">
            {{ t('chat_unlock_description') }}
          </p>
          <button class="deposit-btn">
            {{ t('chat_deposit') }}
          </button>
        </div>
      </div>
    </div>

    <!-- 语言选择器 -->
    <AppSelect ref="appSelectRef" v-model="currentLanguage" :options="languageOptions" :title="t('select_language')"
      :show-trigger="false" @update:model-value="roomChange" />
  </div>
</template>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #292d2e;
  color: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  position: relative;
  padding-bottom: 56px;
  /* 为系统底部导航留出空间 */
}

.status-bar {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  padding: 4px 16px;
  font-size: 14px;
  color: white;
  z-index: 100;
  height: 24px;
}

.icon-info-container {
  width: 28px;
  height: 28px;
  background-color: #3a4142;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.time {
  font-weight: 500;
}

.status-icons {
  display: flex;
  gap: 4px;
  align-items: center;
}

.signal-icon,
.wifi-icon,
.battery-icon {
  width: 17px;
  height: 17px;
  background-size: contain;
  background-repeat: no-repeat;
}

.signal-icon {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 18l-3 3m10-10l-3 3m4-4l-3 3"></path></svg>');
}

.wifi-icon {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12.55a11 11 0 0 1 14.08 0"></path><path d="M1.42 9a16 16 0 0 1 21.16 0"></path><path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path><line x1="12" y1="20" x2="12.01" y2="20"></line></svg>');
}

.battery-icon {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="6" width="18" height="12" rx="2" ry="2"></rect><line x1="23" y1="13" x2="23" y2="11"></line></svg>');
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #323738;
  height: 48px;
}

.header-left {
  display: flex;
  align-items: center;
}

.language-trigger {
  display: flex;
  align-items: center;
  cursor: pointer;
  gap: 1px;
  margin-right: 15px;
}

.global-label {
  font-size: 14px;
  margin-right: 4px;
}

.arrow-down {
  display: inline-block;
  width: 0;
  height: 0;
  margin-right: 16px;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid #ffffff;
}

.online-status {
  display: flex;
  align-items: center;
}

.online-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  background-color: #24ee89;
  border-radius: 50%;
  margin-right: 6px;
}

.online-text {
  font-size: 12px;
  color: #24ee89;
}

.header-right {
  display: flex;
  gap: 4px;
}

.icon-info,
.icon-close {
  width: 12px;
  height: 12px;
  display: inline-block;
  cursor: pointer;
  background-size: contain;
  background-repeat: no-repeat;
  background-color: #3a4142;
  border-radius: 50%;
  padding: 8px;
}

.icon-info {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12" y2="8"></line></svg>');
}

.icon-close {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>');
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px 16px;
  background: #222627;
  position: relative;
}

.message-list {
  display: flex;
  flex-direction: column;
}

.message-item {
  margin-bottom: 16px;
  max-width: 85%;
}

.message-self {
  align-self: flex-end;
  display: flex;
  flex-direction: column;
}


.message-self .message-header {
  justify-content: flex-end;
}

.message-self .user-info {
  flex-direction: row-reverse;
}

.message-admin .username {
  color: #40ffa0;
}

.message-body {
  display: inline-block;
  background-color: #3a4142;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 600;
  word-break: break-word;
  line-height: 16px;
  color: #A8AEB0;
}

.message-self .message-body {
  background-color: #24EE89;
  color: #1E2121;
  align-self: flex-end;
}

.message-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 4px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.username {
  font-size: 10px;
  color: #878d99;
}

.admin-name {
  color: #40ffa0;
}

.message-time {
  font-size: 10px;
  color: #878d99;
}
.time-self{
  color:#A8AEB0;
}

.message-emoji {
  font-size: 16px;
  margin-left: 4px;
}

.chat-input-area {
  position: fixed;
  bottom: 56px;
  /* 为系统底部导航留出空间 */
  left: 0;
  right: 0;
  background-color: #292d2e;
  z-index: 10;
}

.input-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 12px;
  background-color: #292d2e;
}

.input-with-emoji {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #3a4142;
  border-radius: 8px  ;
  padding: 8px 12px;
  position: relative;
  height: 36px;
  border: 1px solid transparent;
  transition: border-color 0.2s ease;
}

.input-with-emoji.input-focused {
  border-color: #24EE89;
}

.message-input {
  flex: 1;
  background-color: transparent;
  border: none;
  color: #ffffff;
  padding: 0 8px;
  font-size: 14px;
  height: 100%;
}

.message-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.emoji-icon {
  width: 20px;
  height: 20px;
  background-size: contain;
  background-repeat: no-repeat;
  cursor: pointer;
  background-color: transparent;
  padding: 0;
  border-radius: 0;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><path d="M8 14s1.5 2 4 2 4-2 4-2"></path><line x1="9" y1="9" x2="9.01" y2="9"></line><line x1="15" y1="9" x2="15.01" y2="9"></line></svg>');
}

/* 表情选择器容器样式 */
.emoji-picker-container {
  width: 100%;
  z-index: 1000;
}

.send-button {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  width: 36px;
  height: 36px;
  background: #3a4142;
  border-radius: 8px;
  border: none;
  cursor: pointer;
}

.activeChat {
  background: #24EE89;
}

.send-icon {
  width: 18px;
  height: 18px;
  background-size: contain;
  background-repeat: no-repeat;
  background-image: url('/img/h5/affiliate-program/chat-send.webp');
}

.footer-spacer {
  height: 56px;
}

/* 弹框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: flex-end;
  justify-content: center;
  z-index: 100;
}

.dialog {
  background-color: #222627;
  padding-top: 5px;
  border-radius: 12px 12px 0 0;
  width: 100%;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  animation: slide-up 0.3s ease-out;
}

@keyframes slide-up {
  from {
    transform: translateY(100%);
  }

  to {
    transform: translateY(0);
  }
}

.dialog-header {
  position: relative;
  padding: 14px;
}

.dialog-header h3 {
  margin: 0;
  font-size: 14px;
  color: #fff;
  text-align: center;
  flex: 1;
}

.close-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  padding: 0;
  cursor: pointer;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #4a5354;
  border-radius: 6px;
}

.close-btn .icon-close {
  width: 14px;
  height: 14px;
  padding: 0;
  transform: translateX(1px);
  background-color: transparent;
}

.dialog-content {
  padding: 12px;
  overflow-y: auto;
}

/* 规则弹框样式 */
.rules-list {
  padding-left: 20px;
  margin: 0;
}

.rules-list li {
  margin-bottom: 4px;
  font-size: 10px;
  line-height: 16px;
  font-weight: 400;
  color: #ffffff;
}

/* 解锁聊天功能弹框样式 */
.unlock-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 16px;
}

.telegram-icon {
  width: 42px;
  height: 42px;
  margin-bottom: 16px;
  background: url('/img/h5/affiliate-program/chat-send.webp') no-repeat center center;
  background-size: contain;
}

.unlock-text {
  font-size: 14px;
  line-height: 1.5;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 20px;
}

.deposit-btn {
  width: 170px;
  padding: 12px 0;
  border: none;
  border-radius: 8px;
  background: linear-gradient(90deg, #24ee89 0%, #9fe871 100%);
  box-shadow:
    0px -2px 0px 0px #1dca6a inset,
    0px 0px 12px 0px #23ee884d;
  color: #000;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 10px;
}

.deposit-btn:hover {
  opacity: 0.9;
}

/* 新消息提示样式 */
.more-wrap {
  position: absolute;
  left: 50%;
  bottom: 24px;
  transform: translate(-50%);
  z-index: 100;
  min-width: 220px;
}

.more-messages-btn {
  width: 100%;
  padding: 0;
  border: none;
  border-radius: 8px;
  background: linear-gradient(90deg, #24ee89 0%, #9fe871 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.icon-text {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  white-space: nowrap;
}

.icon-text.stop {
  visibility: visible;
  opacity: 1;
  transition: opacity 0.2s ease;
}

.icon-text.go-down {
  visibility: hidden;
  opacity: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: opacity 0.2s ease;
}

.more-messages-btn:hover .icon-text.stop {
  visibility: hidden;
  opacity: 0;
}

.more-messages-btn:hover .icon-text.go-down {
  visibility: visible;
  opacity: 1;
}

.icon-stop {
  width: 16px;
  height: 16px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>');
  background-repeat: no-repeat;
  background-position: center;
}

.icon-arrow-down {
  width: 16px;
  height: 16px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><polyline points="19 12 12 19 5 12"></polyline></svg>');
  background-repeat: no-repeat;
  background-position: center;
}

/* 时间分割线样式 */
.time-wrap {
  display: flex;
  justify-content: space-between;
  color: #878d99;
  font-size: 10px;
  margin: 12px 0 8px;
  padding: 0 8px;
  text-align: center;
  width: 100%;
}

/* 消息尾部样式 */
.msg-tail {
  height: 1px;
  margin-bottom: 16px;
}

/* 加载骨架屏样式 */
.loading-skeleton {
  animation: pulse 1.5s infinite;
}

.skeleton-header {
  height: 12px;
  width: 120px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  margin-bottom: 8px;
}

.skeleton-body {
  height: 32px;
  width: 200px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

@keyframes pulse {

  0%,
  100% {
    opacity: 0.6;
  }

  50% {
    opacity: 0.3;
  }
}

/* 消息隐藏后的样式 */
.popped-chat-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 16px;
  color: #878d99;
  font-size: 14px;
}
</style>
